import React, {useMemo, useCallback, useEffect, useState, useRef} from 'react';
import {Divider, Select} from 'antd';
import {connect} from 'react-redux';
import renewAction from '~/model/renewBoard';
import {scrollToId} from '~/utils/dom';

import './index.styl';
import CommonSearchBar from '~/page/FineBi/common/CommonSearchBar';
import Carousel from '~/page/FineBi/common/Carousel';
import UserRoundTabs from '~/page/FineBi/common/UserRoundTabs';
import CommonTitle from '~/page/FineBi/common/Title';
import {
    fetchSearchFormOptions,
} from '~/service/renew';
import {userRoundIdx, initUserRoundIdx} from '~/utils/const';
import {convertSearcherParams} from '~/page/FineBi/utils/convert';
import GroupTable from './dynamicTable';
import PersonalTable from './personalTable';
import {
    searchForm,
    getDimensionId,
    pageId,
    initialValues,
    getDefaultDimension,
    toLine,
    rankSelectConfig,
    initRank
} from './config';

export const initDimensionAndValues = [
    {
        dimensionId: `GroupLeaderReport_select_${userRoundIdx}`,
        dimensionName: userRoundIdx,
        // 一轮班 1 二轮班 2
        value: [initUserRoundIdx]
    }
];

const defaultSearchParams = {
    dimensionAndValues: [...initDimensionAndValues],
    smallFilter: [],
    personalFilter: [],
    // handleType 指操作了大组长或者小组长；操作全局的筛选器时，要清空
    handleType: null,
    sortRule: initRank
};

function Index(props) {
    const initDemenstion = (getDefaultDimension()).concat(initDimensionAndValues);
    const {user, renewBoard, dispatch} = props;
    const {roleList} = user;
    const [loading, setLoading] = useState(false);
    const [selectOptions, setSelectOptions] = useState({});
    const [dimensionAndValues, setDimensionAndValues] = useState(initDemenstion);
    const [userRoundValue, setUserRoundValue] = useState(initUserRoundIdx);
    const [searchParams, setSearchParams] = useState(defaultSearchParams);
    const formRef = useRef();

    const hasDZZ = useMemo(() => !!roleList.find(e => e.tag === 'ud_gtxbdzz'), [roleList]);

    const hasXZZ = useMemo(() => !!roleList.find(e => e.tag === 'ud_gtxbxzz'));

    const handleFilter = useCallback((filter, isBig) => {
        if (isBig) {
            // 大组刷选控制小组和个人过滤
            scrollToId('smallGroup');
            setSearchParams({
                ...searchParams,
                smallFilter: filter,
                personalFilter: filter,
                handleType: 'big'
            });
        }
        else {
            // 小组刷选控制个人过滤
            setSearchParams({
                ...searchParams,
                personalFilter: filter,
                handleType: 'small'
            });
        }
    }, [searchParams]);

    // 表单确定
    const handleOk = fieldsValue => {
        let dimension = convertSearcherParams(fieldsValue);
        dimension = dimension.map(ele => ({
            ...ele,
            dimensionId: getDimensionId(0, ele.dimensionName),
            dimensionName: toLine(ele.dimensionName),
        }));
        dimension.push({...initDimensionAndValues[0], value: [userRoundValue]});
        setSearchParams({
            ...defaultSearchParams,
            dimensionAndValues: [...dimension],
        });
    };

    // 表单重置
    const handleReset = e => {
        setSearchParams({
            ...defaultSearchParams,
            dimensionAndValues: [{...initDimensionAndValues[0], value: [userRoundValue]}],
        });
    };

    // 表单change
    const handleItemChange = itemKeyValue => {
        const filterValue = {...itemKeyValue};
        let dimensionValues = [...dimensionAndValues];
        for (const i in filterValue) {
            filterValue[i] = filterValue[i].filter(ele => ele !== '全部');
            formRef.current.formFields.setFieldsValue({
                [i]: filterValue[i]
            });
            dimensionValues = dimensionValues.map(ele => {
                if (ele.dimensionId === getDimensionId(0, i)) {
                    ele.value = filterValue[i];
                }
                return ele;
            });
        }
    };

    // 请求单个表单配置项
    const handleFetchOptions = (
        {key, searchKey, pager, dependItemKey, dependItemValue, isGetingMore, options: curOptions, fieldsValue}
    ) => {
        let permissions = searchForm.map(item => (
            {
                dimensionId: getDimensionId(0, item.key),
                dimensionName: toLine(item.key),
                filterItems: fieldsValue[item.key]
            }
        ));

        permissions = permissions.filter(item => (item.filterItems?.length && item.dimensionName !== userRoundIdx));
        permissions.push({...initDimensionAndValues[0], value: [userRoundValue]});

        const params = {
            pager,
            dimensionId: getDimensionId(0, key),
            dimensionName: toLine(key),
            searchKey,
            permissions,
            unitId: pageId[0].selectID
        };

        fetchSearchFormOptions(params)
            .then(res => {
                const {data, pager} = res;

                let options = data.map(item => (
                    {
                        key: item,
                        value: item,
                        label: item
                    }
                )) || [];

                // 分页时，累加展示
                if (isGetingMore) {
                    options = curOptions.concat(options);
                }

                setSelectOptions({key, options, pager});
            });
    };

    const handleRadioChange = e => {
        const {value} = e.target;
        setUserRoundValue(value);

        let filterDimension = dimensionAndValues.filter(item => item.dimensionName !== userRoundIdx);
        filterDimension = filterDimension.map(ele => ({...ele, value: ['全部']}));
        const newDimensionAndValues = filterDimension.concat([{...initDimensionAndValues[0], value: [value]}]);

        setSearchParams({
            ...defaultSearchParams,
            dimensionAndValues: [...newDimensionAndValues],
        });
        formRef.current.formFields.resetFields();
    };

    const handleRankChange = value => {
        setSearchParams({
            ...searchParams,
            sortRule: value,
            handleType: defaultSearchParams.handleType
        });
    };

    return (
        <div className="renewBoard">
            <Carousel />
            {/* <Title level={2}>大小组及个人续班数据看板</Title> */}
            <CommonTitle
                title="大小组及个人续班数据看板"
                iconDom={(
                    <>
                        <UserRoundTabs
                            onRadioChange={handleRadioChange}
                        />
                        <span className="rankSelect">
                            按
                            &nbsp;
                            <Select
                                onChange={handleRankChange}
                                value={searchParams.sortRule}
                            >
                                {rankSelectConfig.map(config => (
                                    <Select.Option
                                        key={config.value}
                                        value={config.value}
                                    >
                                        {config.label}
                                    </Select.Option>
                                ))}
                            </Select>
                            &nbsp;
                            排名
                        </span>
                    </>
                )}
            />
            <Divider />
            <CommonSearchBar
                loading={loading}
                noCache
                config={searchForm}
                initialValues={initialValues}
                onOk={handleOk}
                onReset={handleReset}
                onItemChange={handleItemChange}
                onfetchOptions={handleFetchOptions}
                selectOptions={selectOptions}
                ref={formRef}
            />
            <div className="tableContainer">
                {/* <div className="func">
                    <Button onClick={clearFilter}>
                        <ClearOutlined />
                        清除联动
                    </Button>
                </div> */}
                {hasDZZ && (
                    <GroupTable
                        title="大组"
                        domId="bigGroup"
                        type="big"
                        viewName="ud_gtxbdzz"
                        filterClick={handleFilter}
                        searchValue={searchParams}
                    />
                )}
                {(hasDZZ || hasXZZ) && (
                    <GroupTable
                        title="小组"
                        domId="smallGroup"
                        type="small"
                        viewName="ud_gtxbxzz"
                        searchValue={searchParams}
                        filterClick={handleFilter}
                    />
                )}
                <PersonalTable
                    title="个人"
                    desc="个人可续人数<50不参与排名"
                    viewName="ud_gtxbgr"
                    searchValue={searchParams}
                    userRoundValue={userRoundValue}
                />
            </div>
        </div>
    );
}

export default connect(s => s)(Index);
